package cn.ltgodm.moj.controller;

import cn.hutool.core.util.StrUtil;
import cn.ltgodm.moj.annotation.AuthCheck;
import cn.ltgodm.moj.common.BaseResponse;
import cn.ltgodm.moj.common.ErrorCode;
import cn.ltgodm.moj.common.ResultUtils;
import cn.ltgodm.moj.exception.BusinessException;
import cn.ltgodm.moj.message.QuestionMessageProducer;
import cn.ltgodm.moj.model.dto.questionsubmit.QuestionSubmitAddRequest;
import cn.ltgodm.moj.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import cn.ltgodm.moj.model.entity.Question;
import cn.ltgodm.moj.model.entity.QuestionSubmit;
import cn.ltgodm.moj.model.entity.User;
import cn.ltgodm.moj.model.vo.QuestionSubmitVO;
import cn.ltgodm.moj.model.vo.QuestionVO;
import cn.ltgodm.moj.model.vo.UserVO;
import cn.ltgodm.moj.service.JudgeFeignClient;
import cn.ltgodm.moj.service.QuestionService;
import cn.ltgodm.moj.service.QuestionSubmitService;
import cn.ltgodm.moj.service.UserFeignClient;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.CompletableFuture;

/**
 * 题目提交接口
 *
 * @author ltgodm
 * @date 2024-03-13 13:58:53
 */
@RestController
@RequestMapping("/submit")
@Slf4j
public class QuestionSubmitController {

    @Resource
    private QuestionSubmitService questionSubmitService;

    @Resource
    private UserFeignClient userFeignClient;

    @Resource
    private JudgeFeignClient judgeFeignClient;

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionMessageProducer questionMessageProducer;

    /**
     * 提交题目
     *
     * @param questionSubmitAddRequest
     * @param request
     * @return resultNum
     */
    @PostMapping("/")
    public BaseResponse<Long> doSubmitQuestion(@RequestBody QuestionSubmitAddRequest questionSubmitAddRequest,
                                               HttpServletRequest request) {
        if (questionSubmitAddRequest == null || questionSubmitAddRequest.getQuestionId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 登录才能提交题目
        final User loginUser = userFeignClient.getLoginUser(request);
        long questionSubmitId = questionSubmitService.doQuestionSubmit(questionSubmitAddRequest, loginUser);

        //判题,异步执行
/*        CompletableFuture.runAsync(() -> {
            judgeFeignClient.doJudge(questionSubmitId);
        });*/
        questionMessageProducer.sendMessage("code_exchange", "my_routingKey", StrUtil.toString(questionSubmitId));

        return ResultUtils.success(questionSubmitId);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck()
    public BaseResponse<Page<QuestionSubmitVO>> listQuestionSubmitVOByPage(@RequestBody QuestionSubmitQueryRequest questionSubmitQueryRequest, HttpServletRequest request) {
        long current = questionSubmitQueryRequest.getCurrent();
        long size = questionSubmitQueryRequest.getPageSize();
        Page<QuestionSubmit> questionPage = questionSubmitService.page(new Page<>(current, size), questionSubmitService.getQueryWrapper(questionSubmitQueryRequest));
        User loginUser = userFeignClient.getLoginUser(request);
        return ResultUtils.success(questionSubmitService.getQuestionSubmitVOPage(questionPage, loginUser));
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<QuestionSubmitVO> getQuestionById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QuestionSubmit questionSubmit = questionSubmitService.getById(id);
        if (questionSubmit == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //权限校验
        User loginUser = userFeignClient.getLoginUser(request);
        if (loginUser.getId().compareTo(questionSubmit.getUserId()) != 0 && !userFeignClient.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //获取vo数据
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        UserVO user = UserVO.objToVo(userFeignClient.getById(questionSubmit.getUserId()));
        questionSubmitVO.setUserVO(user);
        Question question = questionService.getById(questionSubmitVO.getQuestionId());
        QuestionVO questionVO = questionService.getQuestionVO(question, request);
        questionSubmitVO.setQuestionVO(questionVO);
        return ResultUtils.success(questionSubmitVO);
    }

}
